/*
 * @lc app=leetcode.cn id=581 lang=javascript
 *
 * [581] 最短无序连续子数组
 */

// @lc code=start
/**
 * @param {number[]} nums
 * @return {number}
 */
var findUnsortedSubarray = function(nums) {
    let n = nums.length
    let i = 0, j = n - 1
    while (i < j && nums[i] <= nums[i+1]) i++
    while (j > 0 && nums[j-1] <= nums[j]) j--
    let p = i, r = j
    while (p <= r) {
        while (i > 0 && nums[p] < nums[i-1]) i--
        while (j < n && nums[p] > nums[j+1]) j++
        p++
    }
    return j > i ? j - i + 1 : 0
};
// @lc code=end

let ans = findUnsortedSubarray([2, 6, 4, 8, 10, 9, 15])
console.log(ans)
